package com.lanxiao.cloud.modules.log.application.listener;

import com.lanxiao.cloud.common.web.bus.event.LogEvent;
import com.lanxiao.cloud.modules.log.application.assembler.LogAssembler;
import com.lanxiao.cloud.modules.log.infrastructure.repository.ILogRepository;
import java.util.function.Function;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author ：qiaoliang
 * @date ：2021-10-15
 */
@Configuration
public class LogCollectListener {

  private final ILogRepository logRepository;
  private final LogAssembler logAssembler;

  public LogCollectListener(
      ILogRepository logRepository,
      LogAssembler logAssembler) {
    this.logRepository = logRepository;
    this.logAssembler = logAssembler;
  }

  @Bean
  public Function<Flux<Message<LogEvent<String>>>, Mono<Void>> logCollectEvent() {
    return flux -> flux.map(message -> {
      logRepository.save(logAssembler.toLog(message.getPayload()));
      return message;
    }).then();
  }

}
